"""
配置模板生成器

用于生成配置文件模板和示例
"""

import os
from pathlib import Path
from typing import Dict, Any, Optional
import yaml


class ConfigTemplate:
    """配置模板生成器"""
    
    @staticmethod
    def generate_config_template() -> Dict[str, Any]:
        """
        生成配置文件模板
        
        Returns:
            配置模板字典
        """
        return {
            "browser": {
                "headless": False,
                "timeout": 30000,
                "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
                "args": [
                    "--no-sandbox",
                    "--disable-dev-shm-usage",
                    "--disable-blink-features=AutomationControlled",
                    "--disable-extensions",
                    "--no-first-run",
                    "--disable-default-apps"
                ],
                "proxy": {
                    "enabled": "${PROXY_ENABLED}",
                    "type": "${PROXY_TYPE}",
                    "host": "${PROXY_HOST}",
                    "port": "${PROXY_PORT}"
                }
            },
            "ai": {
                "api_key": "${SILICONFLOW_API_KEY}",
                "base_url": "${AI_BASE_URL}",
                "model": {
                    "text": "${AI_TEXT_MODEL}",
                    "vision": "${AI_VISION_MODEL}"
                },
                "timeout": "${AI_TIMEOUT}",
                "max_retries": "${AI_MAX_RETRIES}"
            },
            "logging": {
                "level": "${LOG_LEVEL}",
                "file": "${LOG_FILE}",
                "max_size": "${LOG_MAX_SIZE}",
                "backup_count": "${LOG_BACKUP_COUNT}",
                "format": "${LOG_FORMAT}",
                "date_format": "${LOG_DATE_FORMAT}"
            },
            "targets": {
                "base_url": "${TARGET_BASE_URL}",
                "baidu_pan_url": "${BAIDU_PAN_URL}",
                "timeout": "${TARGET_TIMEOUT}",
                "retry_count": "${TARGET_RETRY_COUNT}"
            },
            "security": {
                "encryption_enabled": "${ENCRYPTION_ENABLED}",
                "encryption_password": "${CONFIG_ENCRYPTION_PASSWORD}",
                "api_rate_limit": "${API_RATE_LIMIT}",
                "max_concurrent_requests": "${MAX_CONCURRENT_REQUESTS}"
            },
            "performance": {
                "page_load_timeout": "${PAGE_LOAD_TIMEOUT}",
                "element_wait_timeout": "${ELEMENT_WAIT_TIMEOUT}",
                "screenshot_quality": "${SCREENSHOT_QUALITY}",
                "cache_enabled": "${CACHE_ENABLED}",
                "cache_size": "${CACHE_SIZE}"
            }
        }
    
    @staticmethod
    def generate_env_template() -> Dict[str, str]:
        """
        生成环境变量模板
        
        Returns:
            环境变量模板字典
        """
        return {
            # AI服务配置
            "SILICONFLOW_API_KEY": "your_siliconflow_api_key_here",
            "AI_BASE_URL": "https://api.siliconflow.cn/v1",
            "AI_TEXT_MODEL": "Qwen/Qwen2.5-72B-Instruct",
            "AI_VISION_MODEL": "Qwen/Qwen2.5-VL-72B-Instruct",
            "AI_TIMEOUT": "30",
            "AI_MAX_RETRIES": "3",
            
            # 代理配置
            "PROXY_ENABLED": "true",
            "PROXY_TYPE": "socks5",
            "PROXY_HOST": "127.0.0.1",
            "PROXY_PORT": "10801",
            
            # 浏览器配置
            "BROWSER_HEADLESS": "false",
            "BROWSER_TIMEOUT": "30000",
            
            # 日志配置
            "LOG_LEVEL": "INFO",
            "LOG_FILE": "logs/gamer520.log",
            "LOG_MAX_SIZE": "10MB",
            "LOG_BACKUP_COUNT": "5",
            "LOG_FORMAT": "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
            "LOG_DATE_FORMAT": "%Y-%m-%d %H:%M:%S",
            
            # 目标网站配置
            "TARGET_BASE_URL": "https://www.gamer520.com/73454.html",
            "BAIDU_PAN_URL": "https://pan.baidu.com",
            "TARGET_TIMEOUT": "30",
            "TARGET_RETRY_COUNT": "3",
            
            # 安全配置
            "ENCRYPTION_ENABLED": "false",
            "CONFIG_ENCRYPTION_PASSWORD": "your_encryption_password_here",
            "API_RATE_LIMIT": "60",
            "MAX_CONCURRENT_REQUESTS": "5",
            
            # 性能配置
            "PAGE_LOAD_TIMEOUT": "30000",
            "ELEMENT_WAIT_TIMEOUT": "10000",
            "SCREENSHOT_QUALITY": "80",
            "CACHE_ENABLED": "true",
            "CACHE_SIZE": "100",
            
            # 开发配置
            "DEBUG": "false",
            "ENVIRONMENT": "development"
        }
    
    @classmethod
    def create_config_file(cls, output_path: str, overwrite: bool = False) -> bool:
        """
        创建配置文件
        
        Args:
            output_path: 输出文件路径
            overwrite: 是否覆盖已存在的文件
            
        Returns:
            是否成功创建
        """
        output_path = Path(output_path)
        
        if output_path.exists() and not overwrite:
            print(f"配置文件已存在: {output_path}")
            return False
        
        # 确保目录存在
        output_path.parent.mkdir(parents=True, exist_ok=True)
        
        # 生成配置模板
        config_template = cls.generate_config_template()
        
        # 写入文件
        with open(output_path, 'w', encoding='utf-8') as f:
            yaml.dump(config_template, f, default_flow_style=False, allow_unicode=True, indent=2)
        
        print(f"配置文件已创建: {output_path}")
        return True
    
    @classmethod
    def create_env_file(cls, output_path: str, overwrite: bool = False) -> bool:
        """
        创建环境变量文件
        
        Args:
            output_path: 输出文件路径
            overwrite: 是否覆盖已存在的文件
            
        Returns:
            是否成功创建
        """
        output_path = Path(output_path)
        
        if output_path.exists() and not overwrite:
            print(f"环境变量文件已存在: {output_path}")
            return False
        
        # 确保目录存在
        output_path.parent.mkdir(parents=True, exist_ok=True)
        
        # 生成环境变量模板
        env_template = cls.generate_env_template()
        
        # 写入文件
        with open(output_path, 'w', encoding='utf-8') as f:
            f.write("# Gamer520 自动化工具配置文件\n")
            f.write("# 请根据实际情况修改以下配置\n\n")
            
            # 按类别组织环境变量
            categories = {
                "AI服务配置": ["SILICONFLOW_API_KEY", "AI_BASE_URL", "AI_TEXT_MODEL", "AI_VISION_MODEL", "AI_TIMEOUT", "AI_MAX_RETRIES"],
                "代理配置": ["PROXY_ENABLED", "PROXY_TYPE", "PROXY_HOST", "PROXY_PORT"],
                "浏览器配置": ["BROWSER_HEADLESS", "BROWSER_TIMEOUT"],
                "日志配置": ["LOG_LEVEL", "LOG_FILE", "LOG_MAX_SIZE", "LOG_BACKUP_COUNT", "LOG_FORMAT", "LOG_DATE_FORMAT"],
                "目标网站配置": ["TARGET_BASE_URL", "BAIDU_PAN_URL", "TARGET_TIMEOUT", "TARGET_RETRY_COUNT"],
                "安全配置": ["ENCRYPTION_ENABLED", "CONFIG_ENCRYPTION_PASSWORD", "API_RATE_LIMIT", "MAX_CONCURRENT_REQUESTS"],
                "性能配置": ["PAGE_LOAD_TIMEOUT", "ELEMENT_WAIT_TIMEOUT", "SCREENSHOT_QUALITY", "CACHE_ENABLED", "CACHE_SIZE"],
                "开发配置": ["DEBUG", "ENVIRONMENT"]
            }
            
            for category, keys in categories.items():
                f.write(f"# {category}\n")
                for key in keys:
                    if key in env_template:
                        f.write(f"{key}={env_template[key]}\n")
                f.write("\n")
        
        print(f"环境变量文件已创建: {output_path}")
        return True
    
    @classmethod
    def create_all_templates(cls, base_dir: str = ".", overwrite: bool = False) -> Dict[str, bool]:
        """
        创建所有模板文件
        
        Args:
            base_dir: 基础目录
            overwrite: 是否覆盖已存在的文件
            
        Returns:
            创建结果字典
        """
        base_dir = Path(base_dir)
        results = {}
        
        # 创建配置文件模板
        config_path = base_dir / "src" / "config" / "config.template.yaml"
        results["config_template"] = cls.create_config_file(config_path, overwrite)
        
        # 创建环境变量模板
        env_path = base_dir / ".env.template"
        results["env_template"] = cls.create_env_file(env_path, overwrite)
        
        # 更新现有的.env.example
        env_example_path = base_dir / ".env.example"
        results["env_example"] = cls.create_env_file(env_example_path, overwrite)
        
        return results


def main():
    """主函数，用于命令行调用"""
    import argparse
    
    parser = argparse.ArgumentParser(description="配置模板生成器")
    parser.add_argument("--config", help="生成配置文件模板")
    parser.add_argument("--env", help="生成环境变量文件模板")
    parser.add_argument("--all", action="store_true", help="生成所有模板文件")
    parser.add_argument("--overwrite", action="store_true", help="覆盖已存在的文件")
    parser.add_argument("--base-dir", default=".", help="基础目录")
    
    args = parser.parse_args()
    
    if args.all:
        results = ConfigTemplate.create_all_templates(args.base_dir, args.overwrite)
        print("模板生成结果:")
        for template, success in results.items():
            status = "成功" if success else "跳过"
            print(f"  {template}: {status}")
    elif args.config:
        ConfigTemplate.create_config_file(args.config, args.overwrite)
    elif args.env:
        ConfigTemplate.create_env_file(args.env, args.overwrite)
    else:
        parser.print_help()


if __name__ == "__main__":
    main()